package com.magist.manage.copyrights.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.magist.core.controller.BaseController;
import com.magist.core.entity.CxtHolder;
import com.magist.core.entity.ResultMessage;
import com.magist.core.exception.BusinessException;
import com.magist.core.util.BeanCopyUtil;
import com.magist.core.util.DateUtil;
import com.magist.core.util.ExcelUtil;
import com.magist.manage.copyrights.dto.CopyrightsDto;
import com.magist.manage.copyrights.entity.Copyrights;
import com.magist.manage.copyrights.export.CopyrightsExportDto;
import com.magist.manage.copyrights.importExcel.CopyrightsImportDto;
import com.magist.manage.copyrights.service.CopyrightsService;
import com.magist.manage.enums.ValidStatusEnum;
import com.magist.manage.util.AuthFilterUtil;
import com.magist.manage.web.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(value="版权接口",tags={"版权接口"})
@RestController
@RequestMapping("/rest/copyrights")
public class RestCopyrightsController extends BaseController {
    @Autowired
    private CopyrightsService copyrightsService;
    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation(value = "保存", notes = "保存接口")
    @RequestMapping(value = "save.do")
    public Object save(@RequestBody CopyrightsDto copyrightsDto) {
        copyrightsService.addCopyRights(copyrightsDto);
        return ResultMessage.success();
    }

    @ApiOperation(value = "更新", notes = "更新接口")
    @RequestMapping(value = "update.do", method = RequestMethod.POST)
    public Object update(@RequestBody CopyrightsDto copyrightsDto) {
        Copyrights oldCopyrights = copyrightsService.getById(copyrightsDto.getId());
        if (oldCopyrights == null)
            throw new BusinessException("无效的数据!");
        ResultMessage result = null;
        if (copyrightsService.updateCopyrights(copyrightsDto) > 0)
            result = ResultMessage.success("操作成功");
        else
            result = ResultMessage.error("操作失败!");
        return result;
    }

    @ApiOperation(value = "列表", notes = "分页查询接口")
    @RequestMapping(value = "page.do", method = RequestMethod.GET)
    public Object page(@ModelAttribute("copyrightsDto") CopyrightsDto copyrightsDto) {
        ResultMessage result = ResultMessage.success();
        Example example = new Example(Copyrights.class);
        example = packExample(example, copyrightsDto);
        AuthFilterUtil.doAddAuthCondition(example,userInfoService.getById(CxtHolder.getUser().getUserId()));
        // 用户加筛选
        PageInfo<Copyrights> pageInfo = copyrightsService.page(example, getPageInfo());
        // 修改人&过期状态set
        List<Copyrights> list = pageInfo.getList();
        PageInfo<CopyrightsDto> pageInfo2 = new PageInfo<CopyrightsDto>();
        BeanUtils.copyProperties(pageInfo, pageInfo2);
        if (!CollectionUtils.isEmpty(list)) {
            ArrayList<CopyrightsDto> copyrightsDtos = new ArrayList<>();
            for (Copyrights copyrights : list) {

                CopyrightsDto rightsDto = BeanCopyUtil.copy(copyrights, CopyrightsDto.class);

                Date now = new Date();
                Date endDate = copyrights.getEndDate();
                String expireStatus = null;
                int monthDiff = DateUtil.getMonthDiff( endDate,now);
                if (monthDiff == 0) {
                    expireStatus = "1个月内到期";
                } else if (monthDiff > 0 && monthDiff < 3) {
                    expireStatus = "3个月内到期";
                } else if (monthDiff >= 3 && monthDiff < 6) {
                    expireStatus = "6个月内到期";
                } else if (monthDiff >= 6) {
                    expireStatus = "6个月以外到期";
                }
                if (now.after(endDate)) {
                    expireStatus = "已到期";
                }
                rightsDto.setExpireStatus(expireStatus);
                copyrightsDtos.add(rightsDto);
            }

            pageInfo2.setList(copyrightsDtos);
        }

        result.setContent(pageInfo2);
        return result;
    }

//    @ApiOperation(value = "删除", notes = "删除接口")
//    @RequestMapping(value = "del.do", method = RequestMethod.POST)
//    public Object del(@ModelAttribute("id") String id) {
//        Copyrights copyrights = copyrightsService.getById(id);
//        if (copyrights == null)
//            throw new BusinessException("无效的数据!");
//        ResultMessage result = null;
//        if (copyrightsService.delete(copyrights) > 0)
//            result = ResultMessage.success("操作成功");
//        else
//            result = ResultMessage.error("操作失败!");
//        return result;
//    }

    @ApiOperation(value = "详情", notes = "详情接口")
    @RequestMapping(value = "info.do", method = RequestMethod.GET)
    public Object info(@ModelAttribute("id") String id,@ModelAttribute("copyrightsNo")String copyrightsNo) {

        Copyrights copyrights = copyrightsService.getById(id);
        if (copyrights == null) {
            copyrights = copyrightsService.findByCopyrightsNo(copyrightsNo);
        }
        if (copyrights == null)
            throw new BusinessException("无效的数据!");
        CopyrightsDto copyrightsDto = new CopyrightsDto();
        BeanUtils.copyProperties(copyrights, copyrightsDto);
        ResultMessage result = ResultMessage.success();
        result.setContent(copyrightsDto);
        return result;
    }

    private Example packExample(Example example, CopyrightsDto copyrightsDto) {
        Date now = new Date();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleted", "F");
        if (StringUtils.isNotEmpty(copyrightsDto.getId()))
            criteria.andEqualTo("id", copyrightsDto.getId());
        // 到期状态
        String expireStatus = copyrightsDto.getExpireStatus();
        if (StringUtils.isNotEmpty(expireStatus)) {
            if (expireStatus.equals("0")) {
                criteria.andLessThanOrEqualTo("endDate", now);
            } else if (Integer.valueOf(expireStatus) > 6) {
                criteria.andGreaterThanOrEqualTo("endDate", DateUtil.addMonths(now, 6));
            } else {
                criteria.andBetween("endDate", now, DateUtil.addMonths(now, Integer.valueOf(copyrightsDto.getExpireStatus())));
            }
        }
        // 结算形式
        if (StringUtils.isNotEmpty(copyrightsDto.getBalanceType()))
            criteria.andEqualTo("balanceType", copyrightsDto.getBalanceType());
        if (StringUtils.isNotEmpty(copyrightsDto.getWorksStatus()))
            criteria.andEqualTo("worksStatus", copyrightsDto.getWorksStatus());
        if (StringUtils.isNotEmpty(copyrightsDto.getSoleFlag()))
            criteria.andEqualTo("soleFlag", copyrightsDto.getSoleFlag());
        if (StringUtils.isNotEmpty(copyrightsDto.getSubRightsFlag()))
            criteria.andEqualTo("subRightsFlag", copyrightsDto.getSubRightsFlag());
        if (StringUtils.isNotEmpty(copyrightsDto.getOriginalCopyrightsFlag()))
            criteria.andEqualTo("originalCopyrightsFlag", copyrightsDto.getOriginalCopyrightsFlag());
        if (StringUtils.isNotEmpty(copyrightsDto.getWorksStatus()))
            criteria.andEqualTo("worksStatus", copyrightsDto.getWorksStatus());
        if (StringUtils.isNotEmpty(copyrightsDto.getContractNo()))
            criteria.andEqualTo("contractNo", copyrightsDto.getContractNo());
        if (StringUtils.isNotEmpty(copyrightsDto.getOnlineStatus()))
            criteria.andEqualTo("onlineStatus", copyrightsDto.getOnlineStatus());



        // 名称/出版社/合同编号/版权号
        String compoundSearch = copyrightsDto.getCompoundSearch();
        if(!StringUtils.isEmpty(compoundSearch)) {
            Example.Criteria criteria2 = example.createCriteria();
            criteria2.orLike("worksName", "%"+compoundSearch+"%");
            criteria2.orLike("publishingName", "%"+compoundSearch+"%");
            criteria2.orLike("contractNo", "%"+compoundSearch+"%");
            criteria2.orLike("copyrightsNo", "%"+compoundSearch+"%");
            example.and(criteria2);
        }


        // 作品背景
        String background = copyrightsDto.getBackground();
        if (!StringUtils.isEmpty(background)) {
            Example.Criteria criteria3 = example.createCriteria();
            String[] backgrounds = background.split(",");
            for (String s : backgrounds) {
                criteria3.orLike("background", "%" + s + "%");
            }
            example.and(criteria3);
        }

        // 授权范围
        String copyrightsRange = copyrightsDto.getCopyrightsRange();
        if (!StringUtils.isEmpty(copyrightsRange)) {
            Example.Criteria criteria4 = example.createCriteria();
            String[] ranges = copyrightsRange.split(",");
            for (String range : ranges) {
                criteria4.orLike("copyrightsRange", "%" + range + "%");
            }
            example.and(criteria4);
        }
        return example;
    }


    @ApiOperation(value = "失效版权", notes = "失效版权")
    @RequestMapping(value = "invalidCopyrights.do", method = RequestMethod.POST)
    public Object invalidContract(@ModelAttribute("id") String id) {
        Copyrights copyrights = copyrightsService.getById(id);
        if (copyrights == null)
            throw new BusinessException("无效的数据!");
        ResultMessage result = null;
        if (copyrightsService.doInvalidCopyrights(id) > 0)
            result = ResultMessage.success("操作成功");
        else
            result = ResultMessage.error("操作失败!");
        return result;
    }



    @ApiOperation(value = "模糊查询版权", notes = "模糊查询版权")
    @RequestMapping(value = "fetchCopyrightsList.do", method = RequestMethod.POST)
    public Object fetchCopyrightsList(@ModelAttribute("copyrightsNo") String copyrightsNo,String contractNo) {
        ResultMessage result = null;
        result = ResultMessage.success();
        Copyrights entity = new Copyrights();
        entity.setCopyrightsNo("%" + copyrightsNo + "%");
        if(!StringUtils.isEmpty(contractNo)) {
            entity.setContractNo("%" + contractNo + "%");
        }
        List<Copyrights> copyrightses = copyrightsService.find(entity);
        result.setContent(copyrightses);
        if (!CollectionUtils.isEmpty(copyrightses)) {
            ArrayList<CopyrightsDto> copyrightsDtos = new ArrayList<>();
            for (Copyrights copyrights : copyrightses) {

                CopyrightsDto rightsDto = BeanCopyUtil.copy(copyrights, CopyrightsDto.class);

                Date now = new Date();
                Date endDate = copyrights.getEndDate();
                String expireStatus = null;
                int monthDiff = DateUtil.getMonthDiff( endDate,now);
                if (monthDiff == 0) {
                    expireStatus = "1个月内到期";
                } else if (monthDiff > 0 && monthDiff < 3) {
                    expireStatus = "3个月内到期";
                } else if (monthDiff >= 3 && monthDiff < 6) {
                    expireStatus = "6个月内到期";
                } else if (monthDiff >= 6) {
                    expireStatus = "6个月以外到期";
                }
                if (now.after(endDate)) {
                    expireStatus = "已到期";
                }
                rightsDto.setExpireStatus(expireStatus);
                copyrightsDtos.add(rightsDto);
            }
            result.setContent(copyrightsDtos);
        }
        return result;
    }


    @ApiOperation(value = "判断版权时间", notes = "判断版权时间(剩余有效期是否大于6个月)")
    @PostMapping(value = "checkCopyrightsDate.do")
    public Object checkCopyrightsDate(@ModelAttribute("copyrightsNo") String copyrightsNo) {
        ResultMessage result = copyrightsService.checkCopyrightsDate(copyrightsNo);
        return result;
    }


    @ApiOperation(value = "批量失效版权", notes = "批量失效版权")
    @RequestMapping(value = "batchInvalid.do", method = RequestMethod.POST)
    public Object batchInvalid(@ModelAttribute("invalidIds") String invalidIds) {
        if(StringUtils.isEmpty(invalidIds)) {
            throw new BusinessException("未选择失效数据");
        }
        String[] invalids = invalidIds.split(",");
        ResultMessage result = null;
        for (String id : invalids) {
            Copyrights copyrights = copyrightsService.getById(id);
            if (copyrights == null)
                throw new BusinessException("无效的数据!");

            if (copyrightsService.doInvalidCopyrights(id) > 0)
                result = ResultMessage.success("操作成功");
            else {
                result = ResultMessage.error("操作失败!");
                return result;
            }
        }
        return result;
    }

    @ApiOperation(value="excel导出", notes="excel导出")
    @RequestMapping(value = "exportExcel.do", method = RequestMethod.GET)
    public void exportExcel(@ModelAttribute("copyrightsDto") CopyrightsDto copyrightsDto, HttpServletResponse response) {
        Example example = new Example(Copyrights.class);
        example = packExample(example, copyrightsDto);
        AuthFilterUtil.doAddAuthCondition(example,userInfoService.getById(CxtHolder.getUser().getUserId()));
        PageHelper.startPage(1, Integer.MAX_VALUE-1,"SHOW_ID DESC");
        List<Copyrights> copyrightses = copyrightsService.find(example);

        List<CopyrightsExportDto> copyrightsDtos = new ArrayList<CopyrightsExportDto>();
        if (!CollectionUtils.isEmpty(copyrightses)) {
            for (Copyrights copyrights : copyrightses) {
                CopyrightsExportDto rightsDto = BeanCopyUtil.copy(copyrights, CopyrightsExportDto.class);

                Date now = new Date();
                Date endDate = copyrights.getEndDate();
                String expireStatus = null;
                int monthDiff = DateUtil.getMonthDiff( endDate,now);
                if (monthDiff == 0) {
                    expireStatus = "1个月内到期";
                } else if (monthDiff > 0 && monthDiff < 3) {
                    expireStatus = "3个月内到期";
                } else if (monthDiff >= 3 && monthDiff < 6) {
                    expireStatus = "6个月内到期";
                } else if (monthDiff >= 6) {
                    expireStatus = "6个月以外到期";
                }
                if (now.after(endDate)) {
                    expireStatus = "已到期";
                }
                rightsDto.setExpireStatus(expireStatus);
                copyrightsDtos.add(rightsDto);
            }
        }
        //导出操作
        ExcelUtil.exportExcel(copyrightsDtos,"版权列表","版权列表",CopyrightsExportDto.class,DateUtil.toString(new Date(),DateUtil.yyyy_MM_dd)+ "版权列表.xls",response);
    }

    @ApiOperation(value="excel导入", notes="excel导入,模板下载路径(47.96.144.33:8080/版权导入模板.xlsx)")
    @PostMapping("importExcel.do")
    public Object importExcel(@RequestParam(value="file") MultipartFile file){
        List<CopyrightsImportDto> copyrightsImportDtos = ExcelUtil.importExcel(file, 15, 1, CopyrightsImportDto.class);
        List<CopyrightsDto> copyrightsDtos = BeanCopyUtil.copy(copyrightsImportDtos, CopyrightsDto.class);
        copyrightsService.doBatchAdd(copyrightsDtos);
        return ResultMessage.success();
    }

}
